!
! pokus o algoritmus s vetvenim, ktery neprohledvava
! v cyklech ale jen s pouzitim rekurse
!

module modzkus

  integer, parameter :: n = 3
  integer :: nvolani = 0
  integer :: a(n),b(n)
  logical :: volna(n)
  real :: x1(n), x2(n)

contains

recursive subroutine zkus(i)

  integer :: i,j,l,k
  real :: s,d,dd,ns
  logical :: nalezena

  nvolani = nvolani + 1
 ! write(*,*) i,":",volna,nvolani

  nalezena = .false.
  do j = 1, n
!     do k =1,n
!        dd = abs((x2(j) - x2(1)) -  (x1(i) - x1(1)))
        !    write(*,*) i,j,dd,a
 
        if( volna(j) )then
           nalezena = .true.
           a(i) = j
           b(j) = i
           volna(j) = .false.
           ! vypocet dd
           if( i > 1 .and. j > 1 ) then
              do l = 2, i - 1
                 do k = 2, j - 1
                    dd = max(abs((x2(j) - x2(k)) - (x1(i) - x1(l))),dd)
                 enddo
              enddo
           else
              dd = 0.0!huge(dd)
           endif
           if( i < n  .and. dd < 0.1 )then 
              call zkus(i+1)
           else
              ns = count(mask= .not. volna)
              d = sum(x2 - x1(b),mask=.not.volna)/ns
              where( volna )
                 b = 0
              end where
              s = sum((x2 - (x1(b) + d))**2,mask=.not.volna)
              d = 0.0
              s = 0.0
              ns = 0
              do l = 1,n
                 if( .not.volna(l)) then
                    dd = x2(l) - x1(b(l))
                    if( abs(dd-10.0) < 0.1 ) then
                       ns = ns + 1
                       d = d + dd
                       s = s + (dd-10.0)**2
                    endif
                 endif
              enddo
              d = d/ns
              s = s/ns
              !if( s < 1.0 ) 
              write(*,*) (l,l=1,n)," -> ",a," :",s,d,ns,dd,volna,b
           endif
           volna(j) = .true.
        endif
!     enddo
enddo

!if( .not. nalezena ) then
!           if( i < n )then
!              call zkus(i+1,j)
!           endif
!           if( j < n )then
!              call zkus(i,j+1)
!           endif
!
!endif

end subroutine zkus

end module modzkus


program zk

use modzkus

  x1 = (/ 0, 10, 20 /) !, 50, 40, 110, 120, 130, 140, 150 /)
  x2 = (/20, 30, 10 /) !, -60, 50, 120, 130, 140, 150, 160 /)
  a = 0
  b = 0

  volna = .true.

  call zkus(1)

  write(*,*) "pocet volani=",nvolani

end program zk

